import router from './index.js'
import store from '@/store'
let timer = null // 加载动画定时器
/**
 * 去某个页面
 * @param {*} options
 * @举例 _.go({name: 'lottie', query:{name:'tom'}}) // 这样就实现了跳转到/lottie页面并且页面传参为name=tom
 */
export const go = (options = {}) => router.push({ path: '', name: '', query: {}, params: {}, ...options }).catch(() => {})
/**
 * 返回前几页
 * @param {*} times -1则为返回前一页   -2则为返回前2页
 * @returns 
 * @举例 goBack(-1)
 */
export const goBack = (function() {
  let prevHref = '' // 上一次的路由
  return function (times = -1){
    prevHref = safeGet(() => window.location.href.split('#')[1].split('?')[0], '')
    router.go(times)
    setTimeout(() => {
      // console.log(prevHref) // 上一页
      // console.log(router.history.current.name) // 当前页面
      if(router.history.current.name == prevHref) {
        goBack(times)
      }
    }, 50)
  }
})()
/**
 * 路由比对函数
 * @param {*} allRouter 全部路由
 * @param {*} userRouter 真实路由
 * @returns 
 * @举例： 
 */
export const compareRoute = function (allRouter = [], userRouter = []) {
  return allRouter.reduce((prev, item) => {
    const {title, icon, activeIcon, children} = userRouter.find(v => item.name == v.name) || {}
    if(_.isArray(children)) { item.children = compareRoute(item.children, children || []) }
    return [...prev, ...title ? [{ ...item, meta: {...item.meta, title, icon, activeIcon }}] : []]
  }, [])
}
//开启load加载动画
export const startLoadAni = function (){
  store.commit('setShowLoadAni', true)
  clearTimeout(timer)
  timer = setTimeout(() => store.commit('setShowLoadAni', false), 800)
}
export const isLogin = function (){
  const token = _.getSessionStorage('token')
  const userId = _.getSessionStorage('userId')
  return token && userId
}